
// 实现与MySQL交互
var mysql = require('mysql');
var $conf = require('../conf/db');
 var $util = require('../util/util');
var $sql = require('./userSqlMapping');

// 使用连接池，提升性能
//$util.extend({},
var pool  = mysql.createPool($conf.mysql);

// 向前台返回JSON方法的简单封装
var jsonWrite = function (res, ret) {
	if(typeof ret === 'undefined') {
		res.json({
			code:'1',
			msg: '操作失败'
		});
	} else {
		res.json(ret);
	}
};

function insertCallBack(result) {			
	
	
}

module.exports = {
	base: function (sql,param,callBack) {
		pool.getConnection(function(err, connection) {
			// 获取前台页面传过来的参数			
			if(err){
				console.log("连接失败"+err);
				return ;
			}		
			connection.query(sql, param,function(err, result){
				if(err){
					console.log(err);
					return ;
				}				
				callBack(result);
				connection.release();
				
			});
		});
	},
	baseErr: function (sql,param,callBack) {
		pool.getConnection(function(err, connection) {
			// 获取前台页面传过来的参数			
			if(err){
				console.log("连接失败"+err);
				return ;
			}		
			connection.query(sql, param,function(err, result){								
				callBack(err,result);
				connection.release();
				
			});
		});
	},
	addBook: function (param,callBack) {		
		this.baseErr($sql.add, [param.name,param.bookNo,param.address],callBack);		
	},
	addSeation:function(param) {		
		this.base($sql.addSeation, [param.title,param.index,param.bookId,param.text],insertCallBack);		
	},
	getBookList:function(callBack){
		this.base($sql.getBookList, [],callBack);
	},
	getSectionListById:function(id,callBack){
		this.base($sql.getSectionListById, [id],callBack);
	},
	getSectionContextById:function(id,callBack){
		this.base($sql.getSectionContextById, [id],callBack);
	},
	getMaxSectionById:function(id,callBack){
		this.base($sql.getMaxSectionById, [id],callBack);
	},
	getBookByName:function(name,callBack){
		this.base($sql.getBookByName, [name],callBack);
	},
	getSectionContextByBookIdIndex:function(id,index,callBack){
		this.base($sql.getSectionContext, [id,index],callBack);
	},
	updateSectionState:function(id,callBack){
		this.base($sql.updateSectionState, [id],callBack);
	}	
};